<template>
  <div class="main" style="margin: 10px">
    <el-card>
      <div>
        <!--工具栏-->
        <div class="head-container">
          <div>
            <!-- 搜索 -->
            <span>
              <el-input v-model="searchKey" clearable placeholder="输入关键字搜索" style="width: 200px" class="filter-item"/>
              <span class="filter-item">
                <el-button type="success" icon="el-icon-search" @click="searchFilter">搜索</el-button>
                <el-button type="warning" icon="el-icon-refresh-left">重置</el-button>
                <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
              </span>
            </span>
            <!-- <span>
              <el-button-group>
                <el-button icon="el-icon-search"></el-button>
                <el-button icon="el-icon-refresh"></el-button>
              </el-button-group>
            </span> -->
          </div>
        </div>
      </div>
      <el-card style="margin-top: 10px">
        <el-table border
          ref="table"
          :data="tableData"
          style="width: 100%"
          row-key="id"
          lazy
          >>
          <el-table-column type="index" label="#" width="55"> </el-table-column>
          <el-table-column prop="userName" label="用户名"> </el-table-column>
          <el-table-column prop="roleName" label="角色" align="center"></el-table-column>
          <el-table-column prop="gender" label="性别" align="center">
            <template slot-scope="scope">
              <el-tag type="success" v-if="scope.row.gender == 0">女</el-tag>
              <el-tag type="warning" v-if="scope.row.gender == 1">男</el-tag>
              <el-tag type="danger" v-if="scope.row.gender == 2">未设置</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="phone" label="电话" align="center"></el-table-column>
          <el-table-column prop="state" label="是否启用" align="center">
            <template slot-scope="scope">
              <el-switch
                @change="changeSwitch(scope.row)"
                v-model="scope.row.state"
                :active-value="1"
                active-text="是"
                :inactive-value="2"
                inactive-text="否"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建日期" align="center">
            <template slot-scope="scope">
              {{ scope.row.createTime | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="250" align="center">
            <template slot-scope="scope">
              <el-button type="success" size="mini" @click="handlePasswordEdit(scope.row)">修改密码</el-button>
              <el-button type="primary" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-card>
    <!-- 分页 -->
    <pagination :total="total" :page.sync="listQuery.current" :limit.sync="listQuery.size" @pagination="getList"/>
    <DialogUser :dialogUser="dialogUser" :formData="formData" @handleSubmit="handleSubmit" @handleSubmitEdit="handleSubmitEdit"></DialogUser>
    <DialogPassword :dialogPassword="dialogPassword" :formData="formData" @handlePasswordSubmit="handlePasswordSubmit"></DialogPassword>
  </div>
</template>

<script>
import { getUserPageList, createUser, deleteUser, updateUserStatus, userUpdate, updatePassword } from "@/api/user";
import DialogUser from "@/components/System/user/dialogUser.vue";
import DialogPassword from "@/components/System/user/dialogPassword.vue";
import Pagination from "@/components/Pagination"; // el分页
export default {
  data() {
    return {
      AddBtnAuth: ["add"],
      tableData: [],
      searchKey: "",
      dialogUser: {
        show: false,
      },
      dialogPassword: {
        show: false,
      },
      //条件查询搜索
      total: 0,
      listQuery: {
        current: 1,
        size: 10,
        userName: undefined,
      },
      formData: {},
    };
  },
  methods:{
    getList() {
      getUserPageList(this.listQuery).then((res) => {
        this.tableData = res.data.records;
        this.total = res.data.total;
        this.listQuery.current = res.data.current;
        this.listQuery.size = res.data.size;

        setTimeout(() => {
          this.listLoading = false;
        }, 1.5 * 1000);
      });
    },
    // 新增按钮触发
    handleAdd() {
      this.dialogUser = {
        show: true,
        title: "新增用户",
        option: "add",
      };
      this.formData = {
        phone: '',
        userName: '',
        gender: 1,
        password: '',
        rid: [],
      };
    },
    //新增提交
    handleSubmit() {
      //将角色转换成字符串
      var sRoles = this.formData.rid;
      this.formData.rid = sRoles.join(',');
      createUser(this.formData).then((res) => {
        if (res.data == true) {
          this.dialogUser.show = false;
          this.$message.success("新增成功！");
          this.getList();
        } else {
          this.dialogUser.show = false;
          this.$message.success(res.message);
        }
      });
    },
    // 编辑按钮触发
    handleEdit(row) {
      var roles = row.rid;
      var ids;
      if (roles != null) {
        var ids = roles.split(",").map(Number);
      }
      this.dialogUser = {
        show: true,
        title: "修改用户",
        option: "edit",
      };
      this.formData = {
        id: row.id,
        userName: row.userName,
        phone: row.phone,
        password: row.password,
        rid: ids,
      };
    },
    //修改密码按钮触发
    handlePasswordEdit(row) {
      this.dialogPassword = {
        show: true,
        title: "修改密码",
        option: "edit",
      };
      this.formData = {
        id: row.id,
      };
    },
    // 提交编辑请求
    handleSubmitEdit() {
      //将角色转换成字符串
      var sRoles = this.formData.rid;
      this.formData.rid = sRoles.join(',');
      userUpdate(this.formData).then((res) => {
        if (res.data == true) {
          this.dialogUser.show = false;
          this.$message.success("修改成功！");
          this.getList();
        } else {
          this.dialogUser.show = false;
          this.$message.success(res.message);
        }
      });
    },
    //提交修改密码请求
    handlePasswordSubmit() {
      updatePassword(this.formData).then((res) => {
        if (res.data === true) {
          this.dialogPassword.show = false;
          this.$message.success("修改成功！");
          this.getList();
        } else {
          this.dialogPassword.show = false;
          this.$message.error("修改失败！");
        }
      });
    },
    //删除
    handleDelete(row) {
      this.$confirm('此操作将永久删除该用户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteUser(row.id).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getList();
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //监听switch事件
    async changeSwitch(row) {
      if(row.id == undefined || row.id == "") {
            this.$message({
            type: "info",
            message: "修改失败！",
          });
      }

      if(row.state == undefined) {
            this.$message({
            type: "info",
            message: "修改失败！",
          });
      }
      updateUserStatus(row.id, row.state).then(res => {
        if (res.data == true) {
            this.$message({
              type: "success",
              message: "修改成功!",
            });
        } else{
            this.$message({
            type: "info",
            message: "修改失败！",
          });
        }
      })
    },
    searchFilter() {
      this.listQuery.userName = this.searchKey;
      this.getList();
    }
  },
  mounted() {
    this.getList();
  },
  components: {
    DialogUser,
    DialogPassword,
    Pagination,
  },
}
</script>

<style lang="scss" scoped>
::v-deep .el-switch.is-disabled {
  opacity: 1;
}
::v-deep .el-switch.is-checked .el-switch__core {
  &:hover {
    cursor: pointer;
  }
}
// 工具栏
.head {
  &-container {
    text-indent: -10px;
    > div {
      display: flex;
      align-items: center;
      justify-content: space-between;
      > span {
        display: flex;
        align-items: center;
      }
      .filter {
        &-item {
          margin-left: 10px;
        }
      }
    }
  }
}
</style>